import { RoleHelper } from "./base.role";

export class Upgrader implements IRole {
    role: RoleType = 'upgrader';
    bodyPart: BodyPartConstant[] = [WORK, CARRY, MOVE];
    priority: 3;
    minCost: 200;

    work(creep: Creep) {
        this.stateSwitch(creep);

        if (creep.memory.working) {
            // 升级
            this.upgradeController(creep);
        } else {
            // 1. 获取存储的能源
            if (RoleHelper.getStoreEnergy(creep)) {
                return;
            }

            // 2. 拾取地上的能源
            if (RoleHelper.pickupEnergy(creep)) {
                RoleHelper.harvestEnergy(creep);
                return;
            }

            // 3. 采集能源
            if (RoleHelper.harvestEnergy(creep)) {
                return;
            }

            return;
        }
    }

    stateSwitch(creep: Creep) {
        if (creep.memory.working === undefined) {
            creep.memory.working = false;
        }

        if (creep.store.getFreeCapacity() === 0) {
            // 背包满了，切换至升级状态
            creep.memory.working = true;
        } else if (creep.store.getUsedCapacity() === 0) {
            // 背包空了，切换至取能状态
            creep.memory.working = false;
        }
    }

    // 升级控制器
    private upgradeController(creep: Creep) {
        const controller = creep.room.controller;
        if (controller) {
            const result = creep.upgradeController(controller);
            if (result === ERR_NOT_IN_RANGE) {
                RoleHelper.moveToTarget(creep, controller, '#00ff00');
            } else if (result === OK) {
                creep.say('⏫升级')
            }
        } else {
            creep.say('❌没有控制器');
        }
    }
}